package action;

import controller.Action;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Curso;
import model.Disciplina;

public class PesquisarMatrizCurricularAction extends Action {

    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        try {

            String acao = request.getParameter("acao");
            request.setAttribute("cursos", Curso.obterCursos());
            request.setAttribute("acao", acao);

            if (!acao.equals("prepararOperacao")) {
                int codCurso = Integer.parseInt(request.getParameter("optCurso"));
                List<Disciplina> disciplinas = Disciplina.obterDisciplinas();
                List<Disciplina> disciplinaExcluir = new ArrayList<Disciplina>();

                Iterator disciplinaIterator = disciplinas.iterator();
                while (disciplinaIterator.hasNext()) {
                    Disciplina disciplina = (Disciplina) disciplinaIterator.next();
                    if (disciplina.getCurso().getCodCurso() != codCurso) {
                        disciplinaExcluir.add(disciplina);
                    }
                }

                disciplinas.removeAll(disciplinaExcluir);

                request.setAttribute("disciplinas", disciplinas);
                request.setAttribute("codCurso", codCurso);
            }

            RequestDispatcher janela = request.getRequestDispatcher("/pesquisarMatrizCurricular.jsp");
            janela.forward(request, response);
        } catch (ServletException e) {
            throw e;
        } catch (IOException e) {
            throw new ServletException(e);
        } catch (SQLException e) {
            throw new ServletException(e);
        } catch (ClassNotFoundException e) {
            throw new ServletException(e);
        }
    }

    @Override
    public void prepararOperacao(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void confirmarOperacao(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}
